var express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const fs = require('fs');
const mysql = require('mysql');
const constant = require('../data/constant');
var archiver = require('archiver');

//下载文件
router.post('/download_single',(req, res, next)=>{
  console.log('正在下载');
  const filePath = req.body.path;
  const fileName = req.body.filename;
  const originalname = req.body.originalname;
  console.log(fileName,filePath);

  var Pool = mysql.createPool({
      'host':constant.DB_HOST_NAME,
      'user':constant.DB_USER,
      'password':constant.DB_PWD,
      'database':constant.DB_NAME,
      'multipleStatements': true // 支持执行多条 sql 语句
  });
  Pool.getConnection( (err,connection) => {
      if(err){
          console.log(err);
          res.send({
              'res':{
                  'ok': 0,
                  'msg':'数据库连接失败'
              }
          });
      }else{
          // 构造sql语句
          let  sql = "update files set download_count = download_count+1 where file_id = ?;"
          let  sqlParams = [
              req.body.file_id
          ];
          connection.query(sql,sqlParams,async (err,data) => {
              if(err){
                  console.log(err);
                  res.statusCode = 500;
                  res.send({
                      'res':{
                          'ok': 0,
                          'msg':'数据库连接失败'
                      }
                  });
              }else{
                  let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                  res_data = JSON.parse(res_data);//把results字符串转为json对象
                  // console.log(res_data);
                  if(res_data.affectedRows == 1){
                    res.setHeader('status',200);
                    res.set({
                        'content-type': 'application/octet-stream',
                        'content-disposition': 'attachment;filename=' + encodeURI(originalname) 
                    })
                    fs.createReadStream(filePath).pipe(res);
                  }else{
                      res.send({
                          res:{
                              ok:0,
                              msg:"请求失败！"
                          }
                      })
                  }
              }
          });
          connection.release();
      }
  });
})

// 批量下载
router.get('/backup_asset',(req,res,next)=>{
  // let filesList = readfiles.readfiles('uploads\\');
  // console.log(filesList);
  // let fileCounter = 0;
  // const zippedFilename = encodeURIComponent('backup.zip');
  // const list = filesList || [];
  // const header = {
  //   'Content-Type': 'application/x-zip',
  //   'Pragma': 'public',
  //   'Expires': '0',
  //   'Cache-Control': 'private, must-revalidate, post-check=0, pre-check=0',
  //   'Content-disposition': 'attachment; filename="' + zippedFilename + '"',
  //   'Transfer-Encoding': 'chunked',
  //   'Content-Transfer-Encoding': 'binary'
  // };
  // 创建文件输出流
  let zipSteam = fs.createWriteStream('temp\\backup.zip');

  // 创建archive实例
  let archive = archiver('zip', {
    zlib: { level: 9 } // 设置压缩级别
  })
  // 存档出错
  archive.on('error', function(err) {
    throw err
  })

  // 使用pipe将两个流连接，开始写压缩包数据
  archive.pipe(zipSteam);

  // 整个文件夹压缩
  archive.directory('uploads\\','backup');
  archive.finalize();

  // 文件输出流结束
  zipSteam.on('close', function() {
    console.log(`总共 ${archive.pointer()} 字节`)
    console.log('archiver完成文件的归档，文件输出流描述符已关闭');
    // fs.unlinkSync('temp\\backup.zip');
    res.setHeader('status',200);
    res.set('Content-Type', 'application/x-zip')
    res.set('Content-Disposition', `attachment; filename='backup.zip'`)
    res.send();
  })
})


module.exports = router;